<?php

namespace app\company\controller;

use app\BaseController;
use app\company\service\PlatformService;
use app\model\PlatformModel;
use app\model\UnitModel;
use app\model\UserModel;
use think\App;

class Platform extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new PlatformModel();
    }

    /**
     * 平台-左侧选项
     * @return bool|string
     */
    public function leftOption(): bool|string
    {
        try {
            $where = [];
            $where[] = ['company_id', '=', $this->userData['company_id']];
            if ($this->userData['type'] == 2) {
                switch ($this->userData['level']) {
                    case 1:
                        $where[] = ['province_id', '=', $this->userData['province_id']];
                        break;
                    case 2:
                        $where[] = ['city_id', '=', $this->userData['city_id']];
                        break;
                    case 3:
                        $where[] = ['area_id', '=', $this->userData['area_id']];
                        break;
                }
            }
            $data = $this->mode->field('id,level,province_id,city_id,area_id,province_name,city_name,area_name')
                ->where($where)->select()->toArray();
            if (empty($data)) return success();
            $PlatformService = new PlatformService($this->app);
            $data = $PlatformService->leftOption($data);
            if ($this->userData['type'] == 2) {
                switch ($this->userData['level']) {
                    case 2:
                        $data = $data[0]['child'];
                        break;
                    case 3:
                        $data = $data[0]['child'][0]['child'];
                        break;
                }
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 平台详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $data = $this->mode->find($id);
            if (!$data) return success();
            $UserModel = new UserModel();
            $UnitModel = new UnitModel();
            switch ($data['level']) {
                case 1:
                    //下属区域平台
                    $data['region_province_num'] = 1;
                    $data['region_city_num'] = $this->mode->where([
                        ['company_id', '=', $data['company_id']],
                        ['province_id', '=', $data['province_id']],
                        ['level', '=', 2],
                    ])->count();
                    $data['region_area_num'] = $this->mode->where([
                        ['company_id', '=', $data['company_id']],
                        ['province_id', '=', $data['province_id']],
                        ['level', '=', 3],
                    ])->count();
                    //下属单位数量
                    $data['unit_count'] = $UnitModel->where([
                        ['company_id', '=', $data['company_id']],
                        ['province_id', '=', $data['province_id']],
                    ])->count();
                    $data['unit_direct'] = $UnitModel->where([
                        ['company_id', '=', $data['company_id']],
                        ['province_id', '=', $data['province_id']],
                        ['level', '=', $data['level']],
                    ])->count();
                    $data['unit_non_direct'] = $data['unit_count'] - $data['unit_direct'];
                    //用户人数限制
                    $data['user_count'] = $data['user_num'];
                    $data['user_count_num'] = $UnitModel->where([
                        ['company_id', '=', $data['company_id']],
                        ['province_id', '=', $data['province_id']],
                    ])->sum('add_user_num');
                    $data['user_surplus_num'] = $data['user_count'] - $data['user_count_num'];
                    break;
                case 2:
                    //下属区域平台
                    $data['region_province_num'] = 0;
                    $data['region_city_num'] = 1;
                    $data['region_area_num'] = $this->mode->where([
                        ['company_id', '=', $data['company_id']],
                        ['province_id', '=', $data['province_id']],
                        ['city_id', '=', $data['city_id']],
                        ['level', '=', 3],
                    ])->count();
                    //下属单位数量
                    $data['unit_count'] = $UnitModel->where([
                        ['company_id', '=', $data['company_id']],
                        ['province_id', '=', $data['province_id']],
                        ['city_id', '=', $data['city_id']],
                    ])->count();
                    $data['unit_direct'] = $UnitModel->where([
                        ['company_id', '=', $data['company_id']],
                        ['province_id', '=', $data['province_id']],
                        ['city_id', '=', $data['city_id']],
                        ['level', '=', $data['level']],
                    ])->count();
                    $data['unit_non_direct'] = $data['unit_count'] - $data['unit_direct'];
                    //用户人数限制
                    $data['user_count'] = $data['user_num'];
                    $data['user_count_num'] = $UnitModel->where([
                        ['company_id', '=', $data['company_id']],
                        ['province_id', '=', $data['province_id']],
                        ['city_id', '=', $data['city_id']],
                    ])->sum('add_user_num');
                    $data['user_surplus_num'] = $data['user_count'] - $data['user_count_num'];
                    break;
                case 3:
                    //下属区域平台
                    $data['region_province_num'] = 0;
                    $data['region_city_num'] = 0;
                    $data['region_area_num'] = 1;
                    //下属单位数量
                    $data['unit_count'] = $UnitModel->where([
                        ['company_id', '=', $data['company_id']],
                        ['province_id', '=', $data['province_id']],
                        ['city_id', '=', $data['city_id']],
                        ['area_id', '=', $data['area_id']],
                    ])->count();
                    $data['unit_direct'] = $data['unit_count'];
                    $data['unit_non_direct'] = 0;
                    //用户人数限制
                    $data['user_count'] = $data['user_num'];
                    $data['user_count_num'] = $UnitModel->where([
                        ['company_id', '=', $data['company_id']],
                        ['province_id', '=', $data['province_id']],
                        ['city_id', '=', $data['city_id']],
                        ['area_id', '=', $data['area_id']],
                    ])->sum('add_user_num');
                    $data['user_surplus_num'] = $data['user_count'] - $data['user_count_num'];
                    break;
            }
            $platform_where = [
                ['company_id', '=', $data['company_id']],
                ['areas_id', '=', $data['areas_id']],
                ['type', '=', 2],
                ['role_id', '=', 0]
            ];
            //平台超管数量
            $data['platform_admin_count'] = $UserModel->where($platform_where)->count();
            //默认管理账号
            $data['platform_admin_username'] = $UserModel->where($platform_where)->value('username');
            //超管账号列表
            $data['user'] = $UserModel->field('id,username,time')
                ->where($platform_where)->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 添加平台
     * @return bool|string
     */
    public function add(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'name|平台名称'  => 'require',
                'province_id|省ID' => 'require|integer',
//                'city_id|市ID' => 'require|integer',
//                'area_id|区ID' => 'require|integer',
                'level|层级' => 'require|in:1,2,3',
                'user|账号' => 'require',
                'index_name|首页展示单位名' => 'require',
            ]);
            $PlatformService = new PlatformService($this->app);
            if ($this->userData['type'] == 2) {
                switch ($this->userData['level']) {
                    case 1:
                        if ($this->userData['province_id'] != $param['province_id']) throw new \Exception('您没有权限创建该层级平台！');
                        break;
                    case 2:
                        if ($this->userData['city_id'] != $param['city_id']) throw new \Exception('您没有权限创建该层级平台！');
                        break;
                    case 3:
                        if ($this->userData['area_id'] != $param['area_id']) throw new \Exception('您没有权限创建该层级平台！');
                        break;
                }
            }
            return $PlatformService->add($param, $this->userData);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 编辑平台
     * @return bool|string
     */
    public function update(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require|integer',
                'name|平台名称'  => 'require',
                'province_id|省ID' => 'require|integer',
//                'city_id|市ID' => 'require|integer',
//                'area_id|区ID' => 'require|integer',
                'level|层级' => 'require|in:1,2,3',
                'user|账号' => 'require',
                'index_name|首页展示单位名' => 'require',
            ]);
            $info = $this->mode->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $param['areas_id'] = match (intval($param['level'])) {
                1 => $param['province_id'],
                2 => $param['city_id'],
                3 => $param['area_id'],
                default => throw new \Exception('参数错误！')
            };
            $UserModel = new UserModel();
            if (!empty($param['user'])) {
                $admin_save = [];
                $usernameData = [];
                foreach ($param['user'] as $item) {
                    $this->validate($item, [
                        'username|账号' => 'require|length:8,18|alphaNum',
                    ], [
                        'username.require' => '账号不能为空',
                        'username.length' => '账号长度不符合要求，8-18位字符',
                        'username.alphaNum' => '账号格式不符合要求，字母或数字',
                    ]);
                    $userInfo = [
                        'company_id' => $this->userData['company_id'],
                        'areas_id' => $param['areas_id'],
                        'platform_id' => $param['id'],
                        'name' => '超级管理员',
                        'type' => 2,
                        'username' => $item['username'],
                        'level' => $param['level'],
                        'province_id' => $param['province_id'],
                        'city_id' => $param['city_id'],
                        'area_id' => $param['area_id'],
                        'province_name' => $param['province_name'],
                        'city_name' => $param['city_name'],
                        'area_name' => $param['area_name']
                    ];
                    if (!empty($item['id'])) {
                        if (!empty($item['password'])) {
                            $this->validate($item, [
                                'password|密码' => 'require|length:8,18',
                            ], [
                                'password.require' => '密码不能为空',
                                'password.length' => '密码长度不符合要求，8-18位字符',
                            ]);
                            $userInfo['password'] = encrypt_password($item['password']);
                        }
                        $userInfo['id'] = $item['id'];
                        if (!empty($param['del']) && in_array($item['id'], $param['del'])) {
                            $param['del'] = array_diff($param['del'], [$item['id']]);
                            $userInfo['is_del'] = 1;
                            $userInfo['del_time'] = time();
                        }
                    } else {
                        $this->validate($item, [
                            'password|密码' => 'require|length:8,18',
                        ], [
                            'password.require' => '密码不能为空',
                            'password.length' => '密码长度不符合要求，8-18位字符',
                        ]);
                        $userInfo['password'] = encrypt_password($item['password']);
                        $userInfo['avatar'] = '/user_avatar/admin.png';
                        $userInfo['time'] = time();
                        $usernameData[] = $item['username'];
                    }
                    $admin_save[] = $userInfo;
                }
                if (count($admin_save) > 0) {
                    $uid = $UserModel->where('username', 'in', $usernameData)->value('id');
                    if ($uid) throw new \Exception('账号已存在！');
                    $UserModel->saveAll($admin_save);
                }
                unset($param['user']);
            }
            if (isset($param['del'])) {
                if (count($param['del']) > 0) {
                    $UserModel->where('id', 'in', $param['del'])->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                }
                unset($param['del']);
            }
            if (!empty($param['rules'])) {
                $rules = explode(',', $param['rules']);
                $param['rules'] = implode(',', PlatformService::AssignPermissions($rules));
            }
            $info->save($param);
            $this->mode->commit();
            return success([], '更新成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 编辑权限
     * @return bool|string
     */
    public function updateRules(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require|integer',
            ]);
            $info = $this->mode->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['rules'])) {
                $rules = explode(',', $param['rules']);
                $param['rules'] = implode(',', PlatformService::AssignPermissions($rules));
            }
            $info->save($param);
            return success([], '更新成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除平台
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $this->mode->startTrans();
            $id = $this->request->param('id');
            $info = $this->mode->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $info->save([
                'is_del' => 1,
                'del_time' => time()
            ]);
            $UserModel = new UserModel();
            $UserModel->where([
                ['company_id', '=', $info['company_id']],
                ['areas_id', '=', $info['areas_id']],
                ['type', '=', 2],
            ])->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            $this->mode->commit();
            return success([], '删除成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 封停平台
     * @return bool|string
     */
    public function status(): bool|string
    {
        $id = $this->request->param('id');
        $status = $this->request->param('status');
        try {
            $this->mode->where('id', '=', $id)->update([
                'status' => $status,
                'status_uptime' => time()
            ]);
            return success([], '修改成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取上级信息
     * @return bool|string
     */
    public function getSuperiorInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $PlatformService = new PlatformService($this->app);
            return success($PlatformService->platformSuperiorInfo($this->userData['company_id'], $param));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 继承上级权限
     * @return bool|string
     */
    public function inheritRules(): bool|string
    {
        $id = $this->request->param('id');
        $this->mode->startTrans();
        try {
            $id = explode(',', $id);
            $PlatformService = new PlatformService($this->app);
            if (is_array($id)) {
                foreach ($id as $v) {
                    $info = $this->mode->find($v);
                    //上级信息
                    $superiorInfo = $PlatformService->platformSuperiorInfo($this->userData['company_id'], [
                        'level' => $info['level'],
                        'province_id' => $info['province_id'],
                        'city_id' => $info['city_id'],
                        'area_id' => $info['area_id'],
                    ]);
                    $this->mode->where('id', '=', $v)->update(['rules' => $superiorInfo['rules']]);
                }
            } else {
                $info = $this->mode->find($id);
                //上级信息
                $superiorInfo = $PlatformService->platformSuperiorInfo($this->userData['company_id'], [
                    'level' => $info['level'],
                    'province_id' => $info['province_id'],
                    'city_id' => $info['city_id'],
                    'area_id' => $info['area_id'],
                ]);
                $this->mode->where('id', '=', $id)->update(['rules' => $superiorInfo['rules']]);
            }
            $this->mode->commit();
            return success([], '继承成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


}
